package com.sta.oldman.tcp;

import com.sta.oldman.coder.TcpMsg;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TcpMsgEncoder {

    public static byte[] encode(TcpMsg msg) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        // 写入头部 (2字节)
        writeShort(baos, msg.getHeader());
        
        // 写入控制字段 (1字节)
        baos.write(msg.getControl());
        
        // 写入命令字段 (1字节)
        baos.write(msg.getCommand());
        
        // 写入长度字段 (2字节)
        writeShort(baos, msg.getLength());
        
        // 写入数据字段
        if (msg.getData() != null) {
            baos.write(msg.getData());
        }
        
        // 写入校验和 (1字节)
        baos.write(msg.getSum());
        
        // 写入尾部 (2字节)
        writeShort(baos, msg.getTail());
        
        return baos.toByteArray();
    }
    
    private static void writeShort(ByteArrayOutputStream baos, short value) {
        baos.write((value >> 8) & 0xFF);
        baos.write(value & 0xFF);
    }
}